package com.neu.servlet.snn;

import com.alibaba.fastjson.JSONObject;
import com.neu.service.snn.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet(name = "AjaxServlet", urlPatterns = {"/AjaxServlet.do"})
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        String flag=request.getParameter("flag");
        HttpSession session=request.getSession();
        String obj=session.getAttribute("pageNum").toString();
        String  pageIndex=(String)session.getAttribute("pageIndex");
        int index=0;
        if(pageIndex==null){
            pageIndex="1";
        }
        switch (flag){
            case "1":
                index=1;
                break;
            case "2":
                index=Integer.parseInt(pageIndex)-1;
                if(index<=0){
                    index=1;
                }
                break;
            case "3":
                index=Integer.parseInt(pageIndex)+1;
                if(index>=Integer.parseInt(obj)){
                    index=Integer.parseInt(obj);
                }
                break;
            case "4":
                index=Integer.parseInt(obj);
                break;
        }
        UserService userService=new UserService();
        List<Map<String,Object>> list=userService.findByPage(index+"",3);
        session.setAttribute("pageIndex",index+"");
        String json=JSONObject.toJSONString(list);
        System.out.println(json);
        PrintWriter out=response.getWriter();
        out.write(json);
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
